package service

import (
	"GoKill/models"
	"GoKill/test"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"strconv"
)

func ProductList(c *gin.Context) {
	test.SaveProInRedis(c)
	var productList []models.Product
	//从redis查询缓存
	result, _ := models.RDB.Get(c, "product").Result()
	//判断是否存在
	if len(result) > 0 {
		//存在，直接返回
		fmt.Println("从redis找")
		err := json.Unmarshal([]byte(result), &productList)
		if err != nil {
			fmt.Println("字符串解析错误", err)
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"redis存在": productList,
		})
		return
	}
	//不存在，从数据库找
	fmt.Println("从数据库找")
	models.DB.Find(&productList)
	productListJson, _ := json.Marshal(productList)
	//redis
	models.RDB.Set(c, "product:", productListJson, 0)
	c.JSON(http.StatusOK, gin.H{"data": productList})
}
func ProductPage(c *gin.Context) {
	var p []models.Product
	db := models.DB
	page, _ := strconv.Atoi(c.Query("page"))
	pageSize, _ := strconv.Atoi(c.Query("page_size"))
	if name, IsExist := c.GetQuery("name"); IsExist == true {
		db = db.Where("name=?", name)
	}
	if id, IsExist := c.GetQuery("id"); IsExist == true {
		db = db.Where("id=?", id)
	}
	if page > 0 && pageSize > 0 {
		db = db.Limit(pageSize).Offset((page - 1) * pageSize)
	}
	if err := db.Find(&p).Error; err != nil {
		fmt.Println(err.Error())
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"data": p,
	})
}
func ProductById(c *gin.Context) {
	var product models.Product
	//param路由参数访问路经要  /:id
	id, _ := strconv.Atoi(c.Param("id"))
	err := models.DB.Where("id=?", id).First(&product).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			c.JSON(
				http.StatusOK, gin.H{
					"data": nil,
				})
			return
		} else {
			c.JSON(
				http.StatusOK, gin.H{
					"error": err.Error(),
				})
		}
	}

	c.JSON(
		http.StatusOK, gin.H{
			"data": product,
		})
}
func SelectProById(id int) models.Product {
	var product models.Product
	err := models.DB.Where("id=?", id).First(&product).Error
	if err != nil {
		return models.Product{}
	}
	return product
}
